package com.doyens.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doyens.common.R;
import com.doyens.entity.Dept;
import com.doyens.service.DeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/dept")
@Api(tags = "部门管理接口")
public class DeptController {
    @Autowired
    private DeptService deptService;

    @GetMapping("/list")
    @ApiOperation(value = "下拉框查询部门名称列表方法")
    public R<List<Dept>> list() {
        return R.success(deptService.list());
    }

    @GetMapping("/page")
    @ApiOperation(value = "页面显示部门信息")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page={}.pageSize={},name={}", page, pageSize, name);
        //构造分页条器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Dept> queryWrapper = new LambdaQueryWrapper<>();
        //构建搜索条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Dept::getDeptName, name);
        //构建排序条件
        queryWrapper.orderByDesc(Dept::getUpdateTime);

//        执行查询
        deptService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    @DeleteMapping
    @ApiOperation(value = "部门删除")
    @CacheEvict(value = "dept", allEntries = true) //清除setmealCache名称下,所有的缓存数据
    public R<String> delete(Integer id) {
        boolean b = deptService.removeById(id);
        if (b){
            return R.success("删除成功");
        }
        return R.error("删除部门失败");
    }

    @PostMapping
    @ApiOperation(value = "部门添加")
    public R<String> save(Dept dept) {
        boolean save = deptService.save(dept);
        if (save){
            return R.success("新增部门成功");
        }
        return R.error("新增部门失败");
    }

    @GetMapping("{deptId}")
    @ApiOperation(value = "根据id查询部门信息")
    public R<Dept> getById(@PathVariable String deptId) {
        Dept dept = deptService.getById(deptId);
        if (dept != null) {
            return R.success(dept);
        }
        return R.error("没有查询到部门信息");
    }

    @PutMapping
    @ApiOperation(value = "修改部门信息")
    public R<String> update(Dept dept) {
        boolean b = deptService.updateById(dept);
        if (b){
            return R.success("修改信息成功");
        }
        return R.error("更新部门信息失败");
    }
}
